/**
 * 04/12/2013
 * 
 * HttpUtils
 * 
 * Copyright GPL
 */
package com.jtmproject.classes;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

/**
 * This class has function to do actions with http
 * @author Javier Tejedor
 */
public class HttpUtils {

	/**
	 * this function returns the value of parameter passed by GET. You can
	 * check if the string is numeric. It is useful for id.
	 * @param actionContext
	 * @param key
	 * @return
	 */
	public static String getGetParameters(
			ActionContext actionContext, String key, boolean numeric) {
		
		String result = null;
		
		HttpServletRequest request = 
				(HttpServletRequest) actionContext.get(
						ServletActionContext.HTTP_REQUEST);
		
		result = request.getParameter(key);
		
		if(numeric){
			if(!isNumeric(result)) {
				return null;
			}
		}
		
		return result;
	}

	/**
	 * this checks if the string passed by parameters is numeric
	 * @param str
	 * @return
	 */
	private static boolean isNumeric(String str) {
	  return str.matches("-?\\d+(\\.\\d+)?");  
	}
	
}
